package com.gable.exhibition.scheduler;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.dao.ContractEstimateSendDao;
import com.gable.exhibition.service.ContractEstimateSendService;
import com.gable.exhibition.util.HttpHelper;
import com.gable.exhibition.view.ContractView;
import com.gable.exhibition.view.ParameterView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mj on 2018/2/27.
 * 预计发货提醒
 */
@Component
public class ContractEstimateSendTask {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${remindDay}")
    Integer remindDay;

    @Value("${remindSendByService}")
    String remindSendByService;

    @Autowired
    ContractEstimateSendDao contractEstimateSendDao;

    /**
     * 每天早上九点跑一次，短信提醒预计发货
     */
    @Scheduled(cron="0 0 9 * * ?")
    public void sendSmsForContractEstimateSend(){
        try {
            ParameterView parameterView = new ParameterView();
            parameterView.setRemindDay(remindDay);

            List<ContractView> contractViews = contractEstimateSendDao.querySendRemindForTask(parameterView);
            if(contractViews != null && contractViews.size() > 0){
                Map<String,String> smsMap = new HashMap<String,String>();
                for(ContractView contractView : contractViews){
                    List<String> mobileList = contractView.getMobileList();
                    StringBuilder sb = new StringBuilder();
                    for(String phone : mobileList){
                        if(StringUtil.isEmpty(phone))
                            continue;
                        sb.append(phone).append(",");
                    }
                    String mobile = sb.substring(0, sb.length() - 1);
                    String contractNo = contractView.getContractNo();
                    String hospitalName = contractView.getHospitalName();

                    String message = hospitalName+"%&"+contractNo;
                    smsMap.put("mobile",mobile);
                    smsMap.put("message",message);
                    String jsonResult = HttpHelper.postRequestResponseBodyAsString(remindSendByService, smsMap);
                    logger.info("合同编号："+contractNo+",短信发送结果:"+jsonResult);
                }
            }
        } catch (Exception e) {
            logger.error("预计发货提醒跑批失败："+e);
        }
    }
}
